package STO_12;

public class Solution {
	boolean[][] vis;
	int[][] steps = { { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, -1 } };

	public boolean exist(char[][] board, String word) {
		char[] words = word.toCharArray();
		
		
		for (int i = 0; i < board.length; i++) {
			for (int j = 0; j < board[0].length; j++) {
				if (DFS(board, words, i, j, 0)) {
					return true;
				}
			}
		}
		return false;

	}

	public boolean DFS(char[][] board, char[] word, int i, int j, int k) {

		if (i < 0 || i >= board.length || j < 0 || j > board[0].length || word[k] != board[i][j]) {
			return false;
		}
		if (k == word.length - 1) {
			return true;
		}
		char temp = board[i][j];
		board[i][j]= '/';
		for (int l = 0; l < steps.length; l++) {
			if (DFS(board, word, i+steps[l][0], j+steps[l][1], k+1)) {
				return true;
			}
			
		}
		board[i][j]= temp;
		
		
		return false;

	}
}
